package com.fagertveit.chainsawrus.graphics;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLES20;

public class Vertices {
	final boolean hasColor;
	final boolean hasTexCoords;
	final int vertexSize;
	final FloatBuffer vertices;
	final ShortBuffer indices;
	
	public Vertices(int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords) {
		this.hasColor = hasColor;
		this.hasTexCoords = hasTexCoords;
		this.vertexSize = (2 + (hasColor?4:0) + (hasTexCoords?2:0)) * 4;
		ByteBuffer buffer = ByteBuffer.allocateDirect(maxIndices * Short.SIZE / 8);
		buffer.order(ByteOrder.nativeOrder());
		vertices = buffer.asFloatBuffer();
		
		if(maxIndices > 0) {
			buffer = ByteBuffer.allocateDirect(maxIndices * Short.SIZE / 8);
			buffer.order(ByteOrder.nativeOrder());
			indices = buffer.asShortBuffer();
		} else {
			indices = null;
		}
	}
	
	public void setVertices(float[] vertices, int offset, int length) {
		this.vertices.clear();
		this.vertices.put(vertices, offset, length);
		this.vertices.flip();
	}
	
	public void setIndices(short[] indices, int offset, int length) {
		this.indices.clear();
		this.indices.put(indices, offset, length);
		this.indices.flip();
	}
	
	public void bind(int positionLocation, int texCoordsLocation, int colorLocation) {
		
		GLES20.glEnableVertexAttribArray(positionLocation);
		
		vertices.position(0);
		GLES20.glVertexAttribPointer(positionLocation, 2, GLES20.GL_FLOAT, false, vertexSize, vertices);
		
		if(hasColor) {
			GLES20.glEnableVertexAttribArray(colorLocation);
			vertices.position(2);
			GLES20.glVertexAttribPointer(positionLocation, 4, GLES20.GL_FLOAT, false, vertexSize, vertices);
		}
		
		if(hasTexCoords) {
			GLES20.glEnableVertexAttribArray(texCoordsLocation);
			vertices.position(hasColor?6:2);
			GLES20.glVertexAttribPointer(positionLocation, 2, GLES20.GL_FLOAT, false, vertexSize, vertices);
		}
	}
	
	public void draw(int primitiveType, int offset, int numVertices) {
		
		if(indices != null) {
			indices.position(offset);
			GLES20.glDrawElements(primitiveType, numVertices, GL10.GL_UNSIGNED_SHORT, indices);
		} else {
			GLES20.glDrawArrays(primitiveType, offset, numVertices);
		}
	}
	
	public void unbind(int texCoordLocation, int colorLocation) {
		
		if(hasTexCoords) {
			GLES20.glDisableVertexAttribArray(texCoordLocation);
		}
		
		if(hasColor) {
			GLES20.glDisableVertexAttribArray(colorLocation);
		}
	}
}
